<!--
 * @Description: 
 * @Author: zzj
 * @Date: 2021-10-18 17:07:25
 * @LastEditors: zzj
 * @LastEditTime: 2021-10-18 20:14:10
-->
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>cms单页面程序</title>
	<script src="https://unpkg.com/vue@next"></script>
	<script src="https://unpkg.com/vue-router@4"></script>
	<script src="https://cdn.bootcdn.net/ajax/libs/qs/6.10.1/qs.min.js"></script>
	<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
</head>
<body>
	<div id="app">
		<h1>{{name}}</h1>
		<router-view></router-view>
	</div>
	<script>
		let Register = {
			template: `
      <div>
          <h3>注册</h3>
          <a href="" @click.prevent="$router.push('/login')">已有账号？登录</a>  
        </div>
      `
		}
		let Login = {
			template: `
        <div>
          <h3>登录</h3>
          <form :model="form">
            <div>用户名 <input type="text" v-model="form.username"/></div>  
            <div>密码 <input type="password" v-model="form.password"/></div>  
            <div><button @click.prevent="loginHandler">登录</button></div>
          </form>
          <a href="" @click.prevent="$router.push('/register')">没有账号？注册</a>  
        </div>
      `,
			data() {
				return {
					form: {}
				}
			},
			methods: {
				loginHandler() {
					let url = "http://121.199.29.84:8001/user/login"
					axios.post(url, this.form).then(({ data: resp }) => {
						if (resp.status === 200) {
							let token = resp.data.token;
							localStorage.setItem('token', token);
							this.$router.push("/home")
						} else {
							alert(resp.message);
						}
					})
				}
			}
		}
		let Home = {
			template: `
        <div>
          <div>
            <a href="" @click.prevent="logoutHandler">退出</a>  
          </div>
          <div style="float:left;width:180px;">
            <div>
              <router-link to="/home/article"> 文章</router-link>  
            </div>
            <div>
              <router-link to="/home/category"> 栏目</router-link>    
            </div>
          </div>  
          <div style="margin-left:200px;padding:.5em">
            <router-view></router-view>  
          </div>
        </div>
      `,
			methods: {
				logoutHandler() {
					localStorage.removeItem('token');
					this.$router.push("/login")
				}
			}
		}
		let Category = {}
		let Article = {
			template: `
        <div>
          <div>
            <button @click="toPublishHandler">添加</button>  
          </div>
          <ul v-if="articles && articles.list.length>0">
            <li v-for="item in articles.list" :key="item.id" style="cursor:pointer">
              <span @click="toDetailsHandler(item.id)">{{item.title}} </span>
              &nbsp;
              <a href="" @click.prevent="delHandler(item)">删除</a>
            </li>
          </ul>
          <div v-else>
            数据不存在
          </div>  
        </div>
      `,
			methods: {
				toDetailsHandler(id) {
					this.$router.push({
						path: '/home/article/details',
						query: { id }
					})
				},
				toPublishHandler() {
					this.$router.push('/home/article/publish')
				}
			},
			setup(props) {
				let ref = Vue.ref;
				let onMounted = Vue.onMounted;
				// 初始化 资讯管理 - 资讯初始化
				// 1. 数据
				let articles = ref({ list: [] })
				// 2. 初始化查询
				let loadArticles = async function () {
					let url = "http://121.199.29.84:8001/article/pageQuery"
					let params = {
						page: 1,
						pageSize: 10
					}
					let token = localStorage.getItem('token')
					let resp = await axios.get(url, {
						params,
						headers: {
							"Authorization": token
						}
					});
					articles.value = resp.data.data;
				}
				// 3. 将初始化查询注册到mounted中，等到生命进行到mounted再执行
				onMounted(loadArticles);

				return {
					articles,
					loadArticles
				}
			}
		}
		let ArticlePublish = {
			template: `
        <div>
          <a href="" @click.prevent="$router.go(-1)">返回</a>
          <div>
            <form :model="form">
              <div>
                标题
                <input type="text" v-model="form.title">  
              </div>  
              <div>
                内容
                <textarea v-model="form.content">  </textarea>
              </div>  
              <div>
                <button @click.prevent="submitHandler">提交</button>  
              </div>
            </form>  
          </div>  
        </div>
      `,
			data() {
				return {
					form: {}
				}
			},
			methods: {
				submitHandler() {
					let url = "http://121.199.29.84:8001/article/saveOrUpdate"
					let token = localStorage.getItem('token')
					axios.post(url, Qs.stringify(this.form), {
						headers: {
							"Content-Type": "application/x-www-form-urlencoded",
							"Authorization": token
						}
					}).then(resp => {
						this.$router.push("/home/article")
					})
				}
			}
		}
		let ArticleDetails = {
			template: `
        <div>
          详情
          <div>{{article}}</div>  

          <h4>推荐</h4>
          <ul v-if="articles && articles.list.length>0">
            <li v-for="item in articles.list" :key="item.id" style="cursor:pointer">
              <span @click="toDetailsHandler(item.id)">{{item.title}} </span>
              &nbsp;
            </li>
          </ul>
          <div v-else>
            数据不存在
          </div>  
        </div>
      `,
			methods: {
				toDetailsHandler(id) {
					this.$router.push({
						path: '/home/article/details',
						query: { id }
					})
				},
			},
			// 在参数更新的时候刷新文章
			beforeRouteUpdate() {
				this.loadArticle();
			},
			setup(props) {
				let ref = Vue.ref;
				let onMounted = Vue.onMounted;
				let useRoute = VueRouter.useRoute;

				let article = ref({})
				let articles = ref({ list: [] })
				let route = useRoute();

				let loadArticle = async function () {
					let url = "http://121.199.29.84:8001/article/findById"
					let id = route.query.id
					let token = localStorage.getItem('token')
					let resp = await axios.get(url, {
						params: { id },
						headers: {
							"Authorization": token
						}
					});
					article.value = resp.data.data;
				}
				let loadArticles = async function () {
					let url = "http://121.199.29.84:8001/article/pageQuery"
					let params = {
						page: 1,
						pageSize: 10
					}
					let token = localStorage.getItem('token')
					let resp = await axios.get(url, {
						params,
						headers: {
							"Authorization": token
						}
					});
					articles.value = resp.data.data;
				}
				onMounted(loadArticle)
				onMounted(loadArticles)

				return {
					article,
					articles,
					loadArticle
				}
			}
		}


		let app = Vue.createApp({
			data() {
				return {
					name: "资讯管理系统"
				}
			}
		})

		let router = VueRouter.createRouter({
			history: VueRouter.createWebHashHistory(),
			routes: [{
				path: '/',
				redirect: '/home'
			}, {
				path: '/register',
				component: Register
			}, {
				path: '/login',
				component: Login
			}, {
				path: '/home',
				component: Home,
				children: [{
					path: 'category',
					component: Category,
				}, {
					path: 'article',
					component: Article
				}, {
					path: 'article/publish',
					component: ArticlePublish
				}, {
					path: 'article/details',
					component: ArticleDetails
				}]
			}]
		})
		router.beforeEach((to, from, next) => {
			// 白名单
			let paths = ["/login", "/register"]
			if (paths.indexOf(to.path) != -1) {
				next();
			}
			// 验证token
			let token = localStorage.getItem('token');
			console.log('监测token', token);
			if (!token) {
				next('/login')
			} else {
				next();
			}
		})
		app.use(router)
		app.mount('#app');
	</script>
</body>
</html>